package com.oj.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import java.io.File;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class HttpClientUtil {
    /**
     * 默认配置信息
     */
    private static RequestConfig DEFAULT_CONFIG;

    private static final String DOWNLOAD_PATH = "D:\\downloadtest\\";

    static {
        DEFAULT_CONFIG = RequestConfig.custom()
                //连接超时时间 毫秒
                .setConnectTimeout(5 * 1000)
                //请求超时时间 毫秒
                .setConnectionRequestTimeout(5 * 1000)
                //读写超时时间
                .setSocketTimeout(5 * 1000).build();
    }

    public static void main(String[] args) throws Exception{
        Map<String,String> head = new HashMap<>(1,1);
        head.put("testhead","head");
        String result = null;
        //1.get请求测试
        //result = doGet("http://127.0.0.1/test/testGet?param=这是参数");
        //2.get请求带头测试
        //result = doGet("http://127.0.0.1/test/testGet?param=testparam",head);
        //3.post请求 form表单提交测试   Content-Type=application/x-www-form-urlencoded; charset=UTF-8
        /*List<NameValuePair> params = new ArrayList<>(2);
        params.add(new BasicNameValuePair("name","zqq"));
        params.add(new BasicNameValuePair("sex","男"));
        result = doPost("http://127.0.0.1/test/testPost",params,head);*/
        //4.post请求 传对象测试 "Content-Type","application/json; charset=UTF-8"
        /*JSONObject paramJson = new JSONObject();
        paramJson.put("name","zqq");
        paramJson.put("sex","男");
        result = doPost("http://127.0.0.1/test/testPostObject",paramJson,null);*/
        //5.下载文件测试
        //downLoadFile("http://127.0.0.1/test/downtest",null,"431.png"); //接口下载文件测试
        //downLoadFile("https://profile.csdnimg.cn/B/5/9/0_zhaoqingquanajax",null,"head.png"); //下载网络文件测试
        //6.上传文件测试
       /* File file = new File("D:\\downloadtest\\123.png");
        InputStream inputStream = new FileInputStream(file);
        result = uploadFile("http://127.0.0.1/test/uploadTest","file",inputStream,file.getName());*/
        //7.多文件上传测试
        //result = uploadFiles("http://127.0.0.1/test/uploadFiles","files","D:\\downloadtest\\");
        //System.out.println(result);
    }

    /**
     * get请求
     * @param url url，参数拼接在后面 ?name=val&name1=var1
     * @return
     */
    public static String doGet(String url){
        HttpGet httpGet = new HttpGet(url);
        httpGet.setConfig(DEFAULT_CONFIG);
        return request(httpGet);
    }

    /**
     * get请求设置请求头
     * @return
     */
    public static String doGet(String url, Map<String,String> header){
        if(header == null){
            throw new RuntimeException("head is not allowed null");
        }
        HttpGet httpGet = new HttpGet(url);
        //添加header
        for (Map.Entry<String, String> e : header.entrySet()) {
            httpGet.addHeader(e.getKey(), e.getValue());
        }
        httpGet.setConfig(DEFAULT_CONFIG);
        return request(httpGet);
    }

    /**
     * 发送请求
     * @param request 请求 HttpPost/HttpGet
     * @return string
     * @throws IOException
     */
    private static String request(HttpUriRequest request) {
        String result = null;
        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build();
             CloseableHttpResponse response = httpClient.execute(request)
        ){
            HttpEntity httpEntity = response.getEntity();
            if(httpEntity != null){
                result = EntityUtils.toString(httpEntity, Charset.forName("utf-8"));
            }
        }catch (Exception e){
            log.error("发送请求错误",e);
        }
        return result;
    }

    /**
     * post请求 form表单方式提交
     * @param url  url
     * @param params 参数
     * @param header 请求头
     * @return
     */
    public static String doPost(String url, List<NameValuePair> params, Map<String,String> header){
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(DEFAULT_CONFIG);
        //默认form表单提交，可加可不加
        httpPost.setHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
        if(params != null){
            //参数
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params,Charset.forName("utf-8"));
            httpPost.setEntity(entity);
        }
        //设置请求头
        addHeader(httpPost,header);
        return request(httpPost);
    }

    /**
     * post请求 对象传参 ，key对应对象的字段名
     * @param url url
     * @param param 参数
     * @param header 请求头
     * @return
     */
    public static String doPost(String url, JSONObject param,Map<String,String> header){
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(DEFAULT_CONFIG);
        httpPost.setHeader("Content-Type","application/json; charset=UTF-8");
        //设置参数
        StringEntity stringEntity = new StringEntity(JSON.toJSONString(param),Charset.forName("utf-8"));
        httpPost.setEntity(stringEntity);
        //设置请求头
        addHeader(httpPost,header);
        return request(httpPost);
    }

    /**
     * 添加请求头
     * @param httpPost post请求
     * @param header 请求头
     */
    private static void addHeader(HttpRequestBase httpPost, Map<String,String> header){
        if(header == null || header.isEmpty()){
            return;
        }
        //添加header
        for (Map.Entry<String, String> e : header.entrySet()) {
            httpPost.addHeader(e.getKey(), e.getValue());
        }
    }

    /**
     * 文件下载
     * @param url 文件url地址
     * @param header 请求头
     * @param fileName 写入本地的文件名称
     */
    public static void downLoadFile(String url,Map<String,String> header,String fileName){
        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()){
            HttpGet httpGet = new HttpGet(url);
            //添加请求头
            addHeader(httpGet,header);
            try (CloseableHttpResponse response = httpClient.execute(httpGet)){
                log.info("响应状态：" + response.getStatusLine());
                HttpEntity httpEntity = response.getEntity();
                if(httpEntity != null){
                    //获取输入流
                    try (InputStream inputStream = httpEntity.getContent()){
                        Path path = Paths.get(DOWNLOAD_PATH + fileName);
                        //文件流存入本地目录
                        Files.copy(inputStream,path);
                    }
                }
            }
        }catch (Exception e){
            log.error("下载文件错误",e);
        }
    }

}
